package com.zhihuishu.micro.course.openapi.app.impl.teacher;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.able.openapi.createCourse.IOnlineExamForCreateCourseService;
import com.zhihuishu.micro.course.dto.ChapterDto;
import com.zhihuishu.micro.course.log.LoggerCollectionEnum;
import com.zhihuishu.micro.course.log.LoggerTemplateUtil;
import com.zhihuishu.micro.course.model.Chapter;
import com.zhihuishu.micro.course.openapi.app.dto.ChapterWebDto;
import com.zhihuishu.micro.course.openapi.app.teacher.ChapterOpenService;
import com.zhihuishu.micro.course.service.ChapterService;
import com.zhihuishu.micro.course.service.CourseBuildService;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;

/**
 * 章接口实现
 * 
 * @author 嵇鹏
 * @descption:
 * 
 * 
 */
@Service("chapterOpenServiceImplForTeacherApp")
public class ChapterOpenServiceImpl implements ChapterOpenService {
    @Resource
    private ChapterService chapterService;
    @Resource
    private CourseBuildService courseBuildService;

    @Resource
    private IOnlineExamForCreateCourseService onlineExamForCreateCourseService;
   
    protected Logger logger=LoggerFactory.getLogger(getClass());
    

    @Override
    public RemoteResult<Integer> addChapter(ChapterWebDto chapterWebDto, Long userId) {
        RemoteResult<Integer> remoteResult = new RemoteResult<Integer>();
        try {
            Assert.notNull(chapterWebDto, "章dto不能为null");
            Assert.notNull(userId, "用户id不能为空");
            chapterWebDto.setId(null);
            ChapterDto chapterDto = BeanHelper.transTo(chapterWebDto, ChapterDto.class);
            chapterDto.setDescription(chapterWebDto.getIntroduction());
            chapterDto.setIsPass(0);// 默认未通过
            chapterService.saveChapterForApp(chapterDto);// 保存章
            chapterService.addChapterOnCourseRedisWithOutChecPassStatus(chapterWebDto.getCourseId(),
                    chapterDto.getId());// 章添加进缓存
            //chapterService.touchChapter(chapterDto.getId());// 保存章详细信息到缓存
            remoteResult.setResult(chapterDto.getId());
            LoggerTemplateUtil.saveLogger(String.format("保存章%d", chapterDto.getId()), userId,
                    LoggerCollectionEnum.chapterCollection, chapterDto.getCourseId());// 日志记录
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
            logger.error("保存章发生错误,参数信息为{}",chapterWebDto,e);
            
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<ChapterWebDto> queryChapterById(Integer chapterId) {
        RemoteResult<ChapterWebDto> remoteResult = new RemoteResult<ChapterWebDto>();
        try {
            Assert.notNull(chapterId, "章id不能为null");
            ChapterDto chapterDto = chapterService.get(chapterId);
            ChapterWebDto chapterWebDto = BeanHelper.transTo(chapterDto, ChapterWebDto.class);
            if (chapterWebDto!=null) {
                chapterWebDto.setIntroduction(chapterDto.getDescription());
            }
            
            remoteResult.setResult(chapterWebDto);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;

    }

    @Override
    public RemoteResult<Void> deleteChapter(Integer chapterId, Long courseId, Long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull(chapterId, "章id不能为空");
            Assert.notNull(courseId, "courseId不能为空");
            Assert.notNull(userId, "用户id不能为null");
            Chapter chapter = new Chapter();
            chapter.setId(chapterId);
            chapter.setIsDeleted(1);
            chapter.setUpdateTime(new Date());
            ChapterDto chapterDto = chapterService.get(chapterId);
            chapterService.deleteChapterById(chapter,courseId);          
            if (!chapterDto.getRank().equals(0)) {//非序章才需要对其他章进行排序
                List<Integer> chapterIds = chapterService.queryIdsByCourseIdAndOredrNunber(courseId,
                        chapterDto.getRank());
                if (chapterIds != null && chapterIds.size() > 0) {
                    chapterService.updateMinusOrderNumByCourseIdAndOrderNumber(courseId, chapterDto.getRank());
                    for (Integer tempChapterId : chapterIds) {
                        chapterService.touchChapter(tempChapterId);// 更新缓存
                    }
                }
            }
           
            chapterService.removeChapterOnCourseRedis(courseId, chapterId);// 清除缓存
            chapterService.removeChapterOnCourseRedisWithOutChecPassStatus(courseId, chapterId);// 清除缓存
            LoggerTemplateUtil.saveLogger(String.format("app删除章%d", chapterId), userId,
                    LoggerCollectionEnum.chapterCollection, courseId);// 日志
            //threadPoolTaskExecutor.execute(task);

        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<Void> updateChapter(ChapterWebDto chapterWebDto, Long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull(chapterWebDto, "chapterWebDto 不能为空");
            Assert.notNull(chapterWebDto.getId(), "id不能为空");
            Chapter chapter = BeanHelper.transTo(chapterWebDto, Chapter.class);
            chapter.setDescription(chapterWebDto.getIntroduction());
            chapter.setUpdateTime(new Date());
            chapterService.updateSelective(chapter);
            chapterService.touchChapter(chapterWebDto.getId());// 更新缓存
            LoggerTemplateUtil.saveLogger(String.format("app更新章%d", chapter.getId()), userId,
                    LoggerCollectionEnum.chapterCollection, chapterWebDto.getCourseId());// 日志记录
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<Void> updateChapterSort(ChapterWebDto chapterWebDto, Long courseId, Long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull(chapterWebDto, "更新对象不能为空");
            Assert.notNull(chapterWebDto.getId(), "主键不能为空");
            Assert.notNull(chapterWebDto.getOriginRank(), "初始位置不能为空");
            Assert.notNull(chapterWebDto.getTargetRank(), "结束位置不能为空");
            Assert.notNull(courseId, "课程id不能为空");
            Assert.notNull(userId, "用户id不能为空");
            Integer orginRank = chapterWebDto.getOriginRank();// 初始位置
            Integer targerRank = chapterWebDto.getTargetRank();// 排序后的位置
            Chapter chapter = new Chapter();
            chapter.setId(chapterWebDto.getId());
            chapter.setOrderNumber(targerRank);
            chapter.setUpdateTime(new Date());
            List<Integer> chapterIds = null;
            
            if(orginRank > targerRank) {// 向前移动(4-->1)
                chapterIds = chapterService.queryChapterIdsContainSmallOrder(courseId, orginRank, targerRank);

            }
            if (orginRank < targerRank) {// 向后移动(1-->4)
                chapterIds = chapterService.queryChapterIdsContainBigOrder(courseId, orginRank, targerRank);
            }
            if (chapterIds != null && chapterIds.size() > 0) {// 需要更改章顺序的id
                for (Integer tempChapterId : chapterIds) {
                    chapterService.touchChapter(tempChapterId);// 更新缓存
                }
            }
            chapterService.updateSelective(chapter);// 更新数据库
            chapterService.touchChapter(chapterWebDto.getId());// 更新缓存

            LoggerTemplateUtil.saveLogger(String.format("app更新章%d顺序由%d变为%d", chapterWebDto.getId(),
                    chapterWebDto.getOriginRank(), chapterWebDto.getTargetRank()), userId,
                    LoggerCollectionEnum.chapterCollection, courseId);//记录日志

        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<Void> cacluCourseStepAndChapterPassStatus(int chapterId, long courseId,
            long userId) {
        RemoteResult<Void> remoteResult=new RemoteResult<Void>();
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("接受到的参数为,courseId={},chapterId={},userId={}",courseId,chapterId,userId);
               
            }
            chapterService.updateChapterPassStatusAndStepStatus(chapterId, courseId, userId);
            
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
            logger.error("计算章是否通过发生异常,参数为:courseId={},chapterId={},userId={}",courseId,chapterId,userId,e);
        }
        return remoteResult;
       
    }

}
